package com.example.skillcinema.onboarding

import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.viewpager2.widget.ViewPager2
import com.example.skillcinema.MainActivity
import com.example.skillcinema.R
import com.example.skillcinema.databinding.FragmentViewPagerBinding
import com.example.skillcinema.onboarding.screens.FirstScreen
import com.example.skillcinema.onboarding.screens.SecondScreen
import com.example.skillcinema.onboarding.screens.ThirdScreen
import com.google.android.material.tabs.TabLayoutMediator


class ViewPagerFragment : Fragment() {
    private var _binding: FragmentViewPagerBinding? = null
    private val binding: FragmentViewPagerBinding
        get() = _binding!!

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _binding = FragmentViewPagerBinding.inflate(inflater, container, false)


        return binding.root
    }

    private fun skip() {
        val sharedPref = activity?.getSharedPreferences(
            getString(R.string.preference_file_key), Context.MODE_PRIVATE
        )
        val editor = sharedPref?.edit()
        editor?.putBoolean(SHARED_PREFFERENCE_ON_BOARDING_KEY, true)
        editor?.apply()
        val intent: Intent = Intent(context, MainActivity::class.java)
        startActivity(intent)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val fragmentList: ArrayList<Fragment> = arrayListOf<Fragment>(
            FirstScreen(),
            SecondScreen(),
            ThirdScreen()
        )
        val viewPagerAdapter: ViewPagerAdapter =
            ViewPagerAdapter(fragmentList, childFragmentManager, lifecycle)
        with(binding) {
            viewPager.adapter = viewPagerAdapter
            viewPager.setPageTransformer(DepthPageTransformer())
            flipPageFrameLayout.setOnClickListener {
                if (viewPager.currentItem < viewPagerAdapter.itemCount - 1)
                    viewPager.currentItem++
                else
                    skip()
            }
            skipTextView.setOnClickListener {
                skip()
            }
            TabLayoutMediator(intoTabLayout, viewPager) { tab, position -> }.attach()
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    companion object {
        val SHARED_PREFFERENCE_ON_BOARDING_KEY = "isOnBoardingComplete"
    }
}